var express = require('express');
var router = express.Router();

const { collarModel, essayContentModel, plModel } = require('../../models/db');

/* GET home page. */
router.get('/', function (req, res, next) {
  res.render('index', { title: 'Express' });
});

router.get('/collar', async function (req, res, next) {
  let data = await collarModel.find()
  res.send(data)
})


router.post('/collar', async function (req, res, next) {
  await collarModel.create(req.body)
  res.send('ok')
})


router.post('/essay', async function (req, res, next) {
  await essayContentModel.create(req.body)
  res.send('ok')
})

router.get('/essay', async function (req, res, next) {
  let data = await essayContentModel.find()
  res.send(data)
})

router.get('/pl', async (req, res) => {
  let { type } = req.query
  console.log(type)

  let obj1 = {}
  if (type != undefined) {
    obj1.type = type
  }
  let ref = await plModel.find().lean()

  let list = []
  let obj = {}
  ref.forEach(item => {
    obj[item._id] = item
  })

  ref.forEach(item => {
    if (!item['pid']) {
      list.push(item)
    } else {
      if (!obj[item['pid']]['children']) {
        obj[item['pid']]['children'] = []
      }
      obj[item['pid']]['children'].push(item)
    }
  })

  res.send(list)
})

router.post('/pl', async (req, res) => {
  await plModel.create(req.body)
  res.send('ok')
})



module.exports = router;    
